package servlets;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

import model.Mesto;
import model.Povlastica;
import model.Prevoznik;
import model.PutnaDuz;
import model.User;
import model.Util;
import app.PMF;

@SuppressWarnings("serial")
public class TripServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		resp.setContentType("text/html; charset=utf-8");

		HttpSession session = req.getSession(true);

		// za prikaz podataka o liniji
		String ID = req.getParameter("ID");
		String showData = req.getParameter("showData");
		// za izmenu podataka o liniji
		String change = req.getParameter("change");
		// ako imamo proslednje nove podake
		String changed = req.getParameter("changed");
		// String changedID = req.getParameter("changedID");
		// za brisanje linije
		String delete = req.getParameter("delete");
		// za dodavanje linije
		String add = req.getParameter("add");
		String fromTown = req.getParameter("fromTown");
		String toTown = req.getParameter("toTown");
		String cena = req.getParameter("cena");
		String polazak = req.getParameter("polazak");
		String dolazak = req.getParameter("dolazak");

		String[] bens = req.getParameterValues("bens");

		User user = (User) session.getAttribute("user");

		// ucitavamo mesta i povlastice
		Vector<Mesto> mesta = Util.getAllEntitiesFromTable(Mesto.class);
		session.setAttribute("allTowns", mesta);

		try {
			// ako imamo user objekat u sesiji
			if (user != null) {

				// ako je prosledjen ID, moramo ucitati putnu duz za akcije
				// pregleda, brisanja i izmene
				if (ID != null) {

					PutnaDuz trip = Util.getEntityFromTableByID(PutnaDuz.class,
							ID);
					session.setAttribute("putnaDuz", trip);
					System.out.println("ID putne duzi: " + trip.getSifra());

					// ako trebamo prikazati povlasticu
					if (showData != null && showData.equals("true")) {
						// redirektovacemo na stranicu za prikaz linije
						RequestDispatcher disp = req
								.getRequestDispatcher("WebContent/showTrip.jsp");
						disp.forward(req, resp);
						return;
					}
					// ako trebamo ici na izmenu,
					if (change != null && change.equals("true")) {

						@SuppressWarnings("unchecked")
						Vector<Povlastica> allBens = (Vector<Povlastica>) session
								.getAttribute("allBens");
						System.out.println("Ucitano: " + allBens.size()
								+ " povlastica");

						session.setAttribute("mfromTown", trip.getMestoOd());
						session.setAttribute("mToTown", trip.getMestoDo());
						session.setAttribute("changedID", ID);

						// redirektovacemo na stranicu za izmenu linije
						RequestDispatcher disp = req
								.getRequestDispatcher("/WebContent/changeTrip.jsp");
						disp.forward(req, resp);
						return;
					}
					// ako trebamo izmeniti podatke
					if (changed != null && changed.equals("true")) {

						System.out.println("Changed: " + changed);

						if (fromTown != null && toTown != null && cena != null
								&& polazak != null && dolazak != null) {

							PersistenceManager pm = PMF.get()
									.getPersistenceManager();
							PutnaDuz pd = Util.getEntityFromTableByID(
									PutnaDuz.class, ID);

							SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");

							pd.setMestoOd(Util.getMestoFromName(fromTown)
									.getSifra());
							pd.setMestoDo(Util.getMestoFromName(toTown)
									.getSifra());
							pd.setCena(Double.parseDouble(cena));
							pd.setPolazak(sdf.parse(polazak));
							pd.setDolazak(sdf.parse(dolazak));

							List<Key> povls = new ArrayList<Key>();
							// prolazimo kroz sve selektovane povlastice u bens
							// i dodajemo ih u putnu liniju
							if (bens != null) {
								for (int i = 0; i < bens.length; i++) {
									Povlastica povl = Util
											.getEntityFromTableByID(
													Povlastica.class, bens[i]);
									povls.add(povl.getSifra());
								}
							}
							pd.setPovlastica(povls);

							// snimamo novu putnu duz
							pm.makePersistent(pd);
							// redirektovacemo na pocetnu stranicu
							RequestDispatcher disp = req
									.getRequestDispatcher("/timeTableServlet");
							disp.forward(req, resp);
							pm.close();
							return;
						} else {
							// nepravilno uneti podaci, ispisati gresku
							RequestDispatcher disp = req
									.getRequestDispatcher("/WebContent/changeTrip.jsp");
							disp.forward(req, resp);
							return;
						}
					}

					if (delete != null && delete.equals("true")) {

						DatastoreService ds = DatastoreServiceFactory
								.getDatastoreService();

						// ucitavamo putnu duz
						PutnaDuz pd = Util.getEntityFromTableByID(
								PutnaDuz.class, ID);
						// pd = Util.getEntityFromTableByID(PutnaDuz.class,
						// pd.getSifra().getId()+"");

						System.out.println("Brisemo putnu duz: " + pd + "...");
						Transaction tx = ds.beginTransaction();
						ds.delete(pd.getSifra());
						tx.commit();
						System.out.println("PutnaDuz obrisana!");

						// redirektovacemo na stranicu za izmenu povlastice
						RequestDispatcher disp = req
								.getRequestDispatcher("/timeTableServlet");
						disp.forward(req, resp);
						return;
					}
				}

				// ako trebamo dodati novu liniju
				if (add != null && add.equals("true")) {

					if (fromTown != null && toTown != null && cena != null
							&& polazak != null && dolazak != null) {

						PersistenceManager pm = PMF.get()
								.getPersistenceManager();

						System.out.println(fromTown + " , " + toTown + " , "
								+ cena + " , " + polazak + " , " + dolazak);

						System.out.println("Ucitavamo prevoznika");
						Prevoznik prevoznik = (Prevoznik) session
								.getAttribute("prevoznik");

						try {
							Mesto mestoOd = Util.getMestoFromName(fromTown);
							Mesto mestoDo = Util.getMestoFromName(toTown);
							int iCena = Integer.parseInt(cena);
							SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
							Date dPolazak = sdf.parse(polazak);
							Date dDolazak = sdf.parse(dolazak);
							// ucitavamo i dodajemo povlastice
							List<Key> povls = new ArrayList<Key>();
							// prolazimo kroz sve selektovane povlastice u bens
							// i dodajemo ih u putnu liniju
							if (bens != null) {
								for (int i = 0; i < bens.length; i++) {
									Povlastica povl = Util
											.getEntityFromTableByID(
													Povlastica.class, bens[i]);
									povls.add(povl.getSifra());
								}
							}

							PutnaDuz pd = new PutnaDuz(iCena, dPolazak,
									dDolazak, povls, mestoOd.getSifra(),
									mestoDo.getSifra(), prevoznik.getSifra());
							pm.makePersistent(pd);

						} catch (Exception e) {
							e.printStackTrace();
							System.out
									.println("ERROR: Neispravno uneti podaci!!!");
							RequestDispatcher disp = req
									.getRequestDispatcher("/WebContent/addTrip.jsp");
							disp.forward(req, resp);
							return;
						}
						// redirektovacemo na pocetnu stranicu
						RequestDispatcher disp = req
								.getRequestDispatcher("/timeTableServlet");
						disp.forward(req, resp);
						pm.close();
						return;
					} else {
						// nepravilno uneti podaci, ispisati gresku
						System.out.println("Neispravni podaci");
						System.out.println(req.getQueryString());
						RequestDispatcher disp = req
								.getRequestDispatcher("WebContent/addTrip.jsp");
						disp.forward(req, resp);
						return;
					}
				}

				// idemo na stranicu za dodavanje nove linije
				RequestDispatcher disp = req
						.getRequestDispatcher("WebContent/addTrip.jsp");
				disp.forward(req, resp);
				return;

			} else {
				System.out.println("addNewBenefitServlet: user == null");
				RequestDispatcher disp = req
						.getRequestDispatcher("/WebContent/logIn.jsp");
				// redirektovacemo na login stranicu
				disp.forward(req, resp);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

}
